﻿using System;
using System.Configuration;
using System.Xml;

namespace CID.Execution.Support.TemplateHandling.Configuration
{
    public class TemplateHandlerElement : ConfigurationElement
    {
        private const string TemplateTypeNameAttribute = "templateTypeName";
        private const string HandlerTypeNameAttribute = "handlerType";

        [ConfigurationProperty(TemplateTypeNameAttribute)]
        public string TemplateTypeName { get { return (string)this[TemplateTypeNameAttribute]; } }

        [ConfigurationProperty(HandlerTypeNameAttribute)]
        public string HandlerTypeName { get { return (string)this[HandlerTypeNameAttribute]; } }

        public Type HandlerType { get; private set; }

        protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
        {
            base.DeserializeElement(reader, serializeCollectionKey);
            try
            {
                HandlerType = LoadHandlerType();
            }
            catch (Exception ex)
            {
                throw new InvalidTemplateHandlingConfigurationException(ex);
            }
        }

        private Type LoadHandlerType()
        {
            var result = Type.GetType(HandlerTypeName, true);

            if (!typeof(ITemplateHandler).IsAssignableFrom(result))
                throw new InvalidCastException(String.Format("The type {0} is not a valid ITemplateHandler", HandlerTypeName));

            var constructor = result.GetConstructor(new Type[] { });
            if (constructor == null)
                throw new Exception(String.Format("The type {0} is not a valid ITemplateHandler", HandlerTypeName));

            return result;
        }
    }
}
